﻿using Furion.DependencyInjection;
using Newtonsoft.Json;
using OnWork.DataCenter.BLL.Base;
using OnWork.DataCenter.BLL.Base.Dto;
using OnWork.DataCenter.BLL.Standard;
using OnWork.DataCenter.DAL.DataCenter;
using OnWork.DataCenter.Utils.Caches;
using SqlSugar;

namespace OnWork.DataCenter.BLL.DataCenter
{
    /// <summary>
    /// MQtt配置
    /// </summary>
    public class DSMqttBLL : BaseBLL<DSMqtt>, IScoped
    {
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<SQLReturn> AddDataAsync(DSMqtt input)
        {
            input.Name = input.Name.Trim();

            bool isExit = await this.Queryable().Where(x => x.Name == input.Name).AnyAsync();
            if (isExit)
            {
                return SQLReturn.AddError($"错误:数据连接名称:{input.Name}已存在!");
            }

            var rows = await this.AddAsync(input); //添加
            ClearCache();
            return SQLReturn.AddSuccess();
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<SQLReturn> DeleteDataAsync(long[] ids)
        {
            if (ids == null || ids.Length == 0)
            {
                return SQLReturn.DelError($"错误:删除Id不存在!");
            }
            var rows = await this.DeleteAsync<DSMqtt>(ids);
            ClearCache();
            return SQLReturn.DelSuccess(rows);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<SQLReturn> UpdateDataAsync(DSMqtt input)
        {
            var old = await base.SingleByIdAsync(input.ID);
            input.Name = input.Name.Trim();
            if (!string.IsNullOrEmpty(input.Name))
            {
                if (Queryable().Where(x => x.Name == input.Name && x.Name != old.Name).Any())
                {
                    return SQLReturn.UpdateError($"错误:数据连接名称:{input.Name}已存在!");
                }
            }
            var rows = await base.UpdateAsync(input);
            ClearCache();
            return SQLReturn.UpdateSuccess(rows);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="option"></param>
        /// <returns></returns>
        public async Task<SQLReturn<List<DSMqtt>>> QueryPagedListAsync(BaseQueryPageInput option)
        {
            var querysql = option.ToQuerySQL<DSMqtt>();

            RefAsync<int> total = 0;
            var query = await Queryable<DSMqtt>()
                .WhereIF(!string.IsNullOrEmpty(querysql.Where), querysql.Where)
                .OrderByIF(!string.IsNullOrEmpty(querysql.Order), $"{querysql.Order}")
                .ToPageListAsync(option.PageIndex, option.PageItems, total);
            return SQLReturn<DSMqtt>.QueryListSuccess(query, total.Value);
        }

        /// <summary>
        /// 查询启用主题的页面
        /// </summary>
        /// <param name="option"></param>
        /// <returns></returns>
        public async Task<List<DSMqtt>> QueryEnableMqttAsync()
        {
            return await Queryable<DSMqtt>()
                .Includes(x => x.Topics.Where(z => z.Enable == true).ToList())
                .Where(x => x.Topics.Any(z => z.Enable))
                .ToListAsync();
        }

        /// <summary>
        /// 查询所有的MQTT服务列表 用于选择
        /// </summary>
        /// <param name="option"></param>
        /// <returns></returns>
        public async Task<List<DSMqtt>> QueryALLMqttAsync()
        {
            return await Queryable<DSMqtt>().ToListAsync();
        }

        /// <summary>
        /// 清除缓存
        /// </summary>
        public void ClearCache()
        {
            MemoryCacheUtil.Removes(CacheKeys.BLLMqttDataStandard);
        }

        /// <summary>
        /// 获取数据标准t
        /// </summary>
        /// <param name="dSMqtt"></param>
        /// <param name="topic"></param>
        /// <returns></returns>
        public async Task<List<MqttProcessStandardDto>> GetDataStandAsync(DSMqtt dSMqtt, string topic)
        {
            //使用内存缓存
            string _timeCacheKey = CacheKeys.BLLMqttDataStandard + "/GetDataStandAsync/" + dSMqtt.ID.ToString();
            var result = await MemoryCacheUtil.GetOrCreateAsync(_timeCacheKey, async entry =>
            {
                var list = new List<MqttProcessStandardDto>();

                //获取当前的top
                var top = dSMqtt.Topics.Where(x => x.Topic == topic).FirstOrDefault();
                if (top != null)
                {
                    //查询对应的数据
                    var storages = await QueryableCopy<DSMqttStorage>().Where(x => x.MqttTopicID == top.ID).ToListAsync();

                    if (storages != null)
                    {
                        foreach (var item in storages)
                        {
                            var ds = new MqttProcessStandardDto();

                            if (!string.IsNullOrEmpty(item.TaskConfigView))
                            {
                                var dto = JsonConvert.DeserializeObject<List<DataStandardTreeDto>>(item.TaskConfigView);
                                if (dto != null)
                                {
                                    ds.StandardsTrees = dto;
                                }
                            }

                            //var standids = item.ProcessConfig.Split(',');
                            //List<DataStandard> dataStandards = new List<DataStandard>();

                            //for (int i = 0; i < standids.Length; i++)
                            //{
                            //    var st = await QueryableCopy<DataStandard>().Where(x => x.ID == long.Parse(standids[i])).SingleAsync();
                            //    dataStandards.Add(st);
                            //}

                            list.Add(ds);
                        }
                    }
                }

                return list;
            });
            return result;
        }
    }
}